<template>
  <div class='personlCard' v-if='showFlag'>
    <div style="position:relative">
      <div style="position:absolute;left:50%;bottom:50%;transform:translate(-50%);font-size:16px;color:#fff;">请选择您要查询的对象</div>
      <img width='100%' src="~@/assets/images/myInfo/info_top.png" alt="">
    </div>
    <div class="Content" @click='editBtn'>
      <div style="display:flex;border-bottom: 1px solid #E5DCC8;border-image: linear-gradient(#E5DCC8,#fff) 30 30;margin: 0 0 0 20px;">
        <div style="flex:1;line-height:46px;">
          <span style="font-size:18px;margin-right:8px;color:#234439;">{{name}}</span>
          <span style="font-size:11px;background:#E3D9C4;padding:3px 10px;color:#333333;border-radius:8px;">本人</span>
        </div>
        <div style="width: 40px;height: 30px;line-height: 35px;background:#efefef; margin-top: 10px; padding-left: 13px;border-top-left-radius: 12px;border-bottom-left-radius: 12px;">
          <!-- <span> -->
            <!-- <img @click='submitUnB();$event.stopPropagation();' style="position:relative;top:13px;width:15px;height:15px;margin-right:25px" src="~@/assets/images/myInfo/info_dele.png" alt=""> -->
          <!-- </span> -->
            <img @click='editBtn();$event.stopPropagation();' style="width:15px;height:15px;" src="~@/assets/images/myInfo/info_modify.png" alt="">
        </div>
      </div>
        <div style="margin:10px 0 0 20px;text-align:left">
          <img style="position:relative;top:3px;width:11px;height:15px;color:#234439;margin-right:17px" src="~@/assets/images/myInfo/info_phonesmile.png" alt="">
          <span style="font-size:14px;line-height:14px">{{mobile}}</span>    
        </div>
        <div style="margin:10px 0 0 20px;text-align:left">
          <img style="position:relative;top:3px;width:17px;color:#234439;height:12px;margin-right:10px" src="~@/assets/images/myInfo/info_ID.png" alt="">
          <span style="font-size:14px;line-height:14px">{{idCard}}</span>
        </div>
    </div>
      <!-- 弹窗 -->
    <van-action-sheet  title="请选择需要编辑的信息" :round='false'
    v-model="infoShow" :actions="actions" @select="onSelect"
    cancel-text="取消" close-on-click-action @cancel="onCancel"
     />
  </div>
</template>
<script lang="ts">
import '../../style/reservaIndex_index.css';
import 'vant/lib/dialog/style';
import 'vant/lib/toast/style';
import 'vant/lib/action-sheet/style';
import { Dialog,ActionSheet,Toast} from 'vant';
import { Component, Vue, Prop } from 'vue-property-decorator';
import { cloudApi,authorizeUrl,authorizeUrlAppid } from '@/api/indexApi';
Component.registerHooks(['beforeRouteUpdate', 'beforeRouteLeave', 'beforeRouteLeave']);
@Component({
   components: {
    [Dialog.name]: Dialog,
    [ActionSheet.name]: ActionSheet
    
  },
})
export default class MainPage extends Vue {
  userData: any = '';
  getUserDate:any=''
  userId: any = '';
  name:string=''
  mobile:any=''
  idCard:any=''
  infoShow:any=false
  actions:any = [{ name: '信息校验' }, { name: '个人信息' }]
  appid:any=''
  code:any='' 
  uid=''
  showFlag:any=false;
  weUniond="";
  created() {
    document.title = '个人名片'
    //  let userData:any={
    //       userId:'',
    //       mobile: "13673838216",
    //       openId: "20b9097509a808701434c2ecbc78229de2be0cf3f15cc94502dc3410f3c99942",
    //       unionId: "09ab7b3e7eec6595dc56e7d5211749e57ff4fcfe9c24a4ce39e8b48152b657fa"
    //  }
    // sessionStorage.setItem("userData",JSON.stringify(userData)) 
    //   this.userData={
    //       userId:'',
    //       mobile: "13673838216",
    //       openId: "20b9097509a808701434c2ecbc78229de2be0cf3f15cc94502dc3410f3c99942",
    //       unionId: "09ab7b3e7eec6595dc56e7d5211749e57ff4fcfe9c24a4ce39e8b48152b657fa"
    //  }
    //   this.getMyBussinessCard()//获取页面数据
    let userData:any=sessionStorage.getItem('userData')||this.$route.query.userData
    if(!userData){//小程序授权而来 
       var address = location.href;
        console.log('zwh授权回来',address)
        this.appid = address.split("appid=")[1].split("&code")[0];
        this.code = address.split("code=")[1].split("&state")[0]
        this.uid = address.split('_userId')[1].split("_html")[0]//userId
        this.weUniond = address.split('_uniond')[1].split("_userId")[0]//userId
        console.log("weUniond==="+this.weUniond)
        sessionStorage.setItem('sourceBack','xiaochengxu')//物理返回键回到小程序标识
        this.getUnionIdAndOpenId()
    }else{
      this.userData = JSON.parse(userData)
      console.log("有数据==="+this.userData)
      this.getMyBussinessCard()//获取页面数据
    }
  }
  mounted() {
      if (window.history && window.history.pushState) {
        // 向历史记录中插入了当前页
        history.pushState(null, null, document.URL);
        window.addEventListener('popstate', this.goBack, false);
     }    
   }
    destroyed () {
      window.removeEventListener('popstate', this.goBack, false);
    }
  goBack () {
    //指定返回路径
     if(sessionStorage.getItem('sourceBack')=='xiaochengxu'){
        sessionStorage.removeItem('sourceBack')
         if((window as any).wx.miniProgram){
          (window as any).wx.miniProgram.navigateBack({
            delta: history.length
          })
        }
      }
  }
  // getUnionIdAndOpenId(){
  //   var _this = this;
  //   cloudApi.getUnionIdAndOpenId({app_id: _this.appid, code: _this.code}).then(function(res: any) {
  //   // cloudApi.getUnionIdAndOpenId({appid: _this.appid, code: _this.code}).then(function(res: any) {
  //       if (res.data) {
  //         if(res.data.openId){
  //           _this.userData={
  //             "openId":res.data.openId,
  //             "unionId":res.data.unionId
  //           }
  //           _this.getMyBussinessCard()//获取页面数据
  //         }else{
  //            Dialog.alert({ title: '温馨提示', message: "未获取到openId" })
  //         }
  //       }else{
  //          Dialog.alert({ title: '温馨提示', message: "网络请求不给力，请稍后重试" })
  //       }
  //     });
  // }
   getUnionIdAndOpenId(){
    var _this = this;
    cloudApi.showInfo({app_id: _this.appid, code: _this.code}).then(function(res: any) {
        if (res.data) {
          if(res.data.openId){
            cloudApi.getThreeidById({id:_this.uid}).then(resDate => {
          //  _this.unionId = resDate.data.unionId
           _this.userData={
              "openId":res.data.openId,
              "unionId":resDate.data.unionid || _this.weUniond,
            }
            sessionStorage.setItem("userData",JSON.stringify(_this.userData));
            _this.getMyBussinessCard()//获取页面数据
            })
          }else{
             Toast('网络请求不给力，请稍后重试');
            //  Dialog.alert({ title: '温馨提示', message: "未获取到openId" })
          }
        }else{
           Toast('网络请求不给力，请稍后重试');
          //  Dialog.alert({ title: '温馨提示', message: "网络请求不给力，请稍后重试" })
        }
      });
  }
  
  onSelect(item:any){
    this.infoShow = false;
    if(item.name=='信息校验'){
      this.myInformation_select_others()
    }else{
      sessionStorage.setItem("getUserDate",JSON.stringify(this.getUserDate))
      this.$router.push({path: 'personalMessage'});//我的信息页
    }
  }
  getMyBussinessCard(){
    const data = {
        openid: this.userData.openId,
        unionid: ""
    }
    let _this = this;
    cloudApi.getMyBussinessCardURL(data).then(res => {
      if(res.status = 200){
        if(res.data.result.length!== 0){
          _this.showFlag=true
          _this.getUserDate =res.data.result[0]
          console.log(_this.getUserDate)
         _this.name=res.data.result[0].name
         _this.userData.userId = res.data.result[0].user_id;
          _this.userData.mobile = _this.getUserDate.mobile_Phone;
         _this.userId=res.data.result[0].user_id
         _this.mobile=_this.getUserDate.mobile_Phone.substring(0,3)+'******'+_this.getUserDate.mobile_Phone.substring(_this.getUserDate.mobile_Phone.length-4)
         _this.idCard=_this.getUserDate.id_card.substring(0,10)+'******'+_this.getUserDate.id_card.substring(_this.getUserDate.id_card.length-2) 
        this.getUserId();
        this.updateUnionidByOpenid();
        }else{//未注册跳转到注册页
          _this.$router.push({path: 'checkPhoneInfo', query: {
              unionId:this.userData.unionId,
              openId: this.userData.openId,
              route:JSON.stringify({path:'personalCard',query: { userDate:this.userData}})
          },}); 
        }
      }
    })
  }
  updateUnionidByOpenid(){
    let parmas = {
      unionid:this.userData.unionId,
      openid:this.userData.openId
    }
    cloudApi.updateUnionidByOpenid(parmas).then(res=>{

    })
  }
  getUserId(){//获得加密userId
      let data= AESEncode({
        userid:this.getUserDate.user_id
      })
      let _this = this;
      cloudApi.desStringUserId({result: data}).then(function(res: any) {
        var data = AESDecode(res.data.result)
        console.log(data)
        _this.userId = data.userid
      }); 
  }
  //解绑
  // submitUnB(){
  //   Dialog.confirm({ title: '温馨提示',message: '是否确认解绑信息？'}) 
  //   .then(() => { 
  //      let data={ //解绑接口添加id入参
  //       open_id: this.userDate.openId,
  //       id:this.getUserDate.id, //id在详情页面带过来
  //       datasource: 'zgs',
  //       unionid: this.getUserDate.unionId||this.userDate.unionId, //新加入参uinionId
  //       phone:this.getUserDate.mobile_Phone,
  //     }
  //     let _this = this;
  //     cloudApi.submitUnBind(data).then(function(res: any) {
  //         if (res.data.result == "1") {
  //           Dialog.alert({title: '温馨提示',message: '解绑成功'}).then(() => {
  //             _this.$router.push({path: 'checkPhoneInfo'}); 
  //           });
  //         }else{
  //           Dialog.alert({ title: '温馨提示',message: '解绑失败'})
  //         }
  //     }); 
  //   }).catch(() => {});
  // }
  editBtn(){ 
    let userData:any={
          "openId":this.userData.openId,
          "mobile":this.getUserDate.mobile_Phone,
          "userId":this.userId,
          "unionId":this.getUserDate.unionId||this.userData.unionId
      }
      sessionStorage.setItem("userData",JSON.stringify(userData))
      if(!this.getUserDate.name || !this.getUserDate.id_card){  
        this.$router.push('idCardInfo');
        return
      }

    //如果信息校验完就不弹出
    let data={ 
        datasource: "zgs",
        id:this.getUserDate.id,
        open_id:this.userData.openId,
        menuID: "",
        mark: ""
      }
      let _this = this;
      cloudApi.toQuery(data).then(function(res: any) {
        if (res.data.result == "bindPlatenumber") {//未绑定
            _this.infoShow =true//弹出底部弹窗
        }else{//跳转到个人信息页
          sessionStorage.setItem("getUserDate",JSON.stringify(_this.getUserDate))
          _this.$router.push({path: 'personalMessage'});
        }
      }); 
  }
  onCancel(){
    this.infoShow =false//弹出底部弹窗
  }
  myInformation_select_others(){
    let faceParmas:any=JSON.stringify({//人脸识别需要参数
        username:this.name,
        idCard:this.getUserDate.id_card,
        cardType:this.getUserDate.type_card,
        userId:this.userData.userId,
        mobile:this.userData.mobile,
        openId:this.userData.openId
        })
    sessionStorage.setItem("faceParmas",faceParmas)
    this.$router.push({path: 'face'})
    // let data={ 
    //     openId:this.userData.openId,
    //     id:this.getUserDate.id, //详情页带过来的
    //     unionid:this.getUserDate.unionId||this.userData.unionId, //新加入参uinionId
    //   }
    //   let _this = this;
    //   cloudApi.getBindQuestion(data).then(function(res: any) {
    //       var data = JSON.parse(decodeURIComponent(atob(res.data.result)));
    //       var ifId = data.id ? data.id : "" //保存返回的id值，以便其他接口调用,如果有id就传id，没有就传空
    //      if (data.policyType == "05") {
    //         let policyShow
    //         let plateNo
    //         if (data.plateNo == "") {//无保单号跳到保单验证页
    //             policyShow ='policy'
    //             plateNo = data.carPolicyNo;
    //         } else {//跳到车牌号页面
    //             plateNo =data.plateNo
    //             if (data.plateNo.length > 7) { //如果是新能源汽车则显示绿色车牌
    //             policyShow ='newCarPolicy'
    //             } else {
    //             policyShow ='carPolicy'   
    //             }
    //         }
    //         _this.$router.push({path: 'checkInfo',query: {carPolicyNo:plateNo,ifId:ifId,policyShow:policyShow}});
    //         } else {
    //             if (data.noCarPolicyNo == "" || data.noCarPolicyNo == undefined) {
    //               Dialog.alert({ title: '温馨提示',message: '暂未查到您在我公司的投保记录，请确认后再次补充投保信息！'})
    //             } else {//非车险日期
    //               _this.$router.push({path: 'checkInfo',query: {carPolicyNo:data.noCarPolicyNo,ifId:ifId,policyShow:"noCarPolicy"}});
    //             }
    //         }
    //         sessionStorage.setItem("secondYZValue","1")
    //   }); 
  }
}
</script>
<style lang="less" scoped>
.personlCard{
  background: url("../../assets/images/myInfo/info_center.png") no-repeat;
  background-size:100% 100%;
  position:absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  /* text-align: center; */
  .Content{
    width: 94%;
    background: url("../../assets/images/myInfo/info_personBg.png") no-repeat;
    background-size:100% 100%;
    height: 140px;
    position: relative;
    left: 50%;
    transform: translateX(-50%);
    padding: 5px 0;
  }
  .btn{
    width: 100%;
    height: 36px;
    line-height: 36px;
    background: #00A08A;
    border-radius: 18px;
    color:#fff;
    font-size: 16px;
  }
  .van-action-sheet {
    width: 95%;
    margin: 10px;
}
  .van-action-sheet__header{
     color:#999;
  }
  .van-action-sheet__cancel{
       color:#00A08A;
  }
  .van-action-sheet__cancel::before{
    background-color: rgba(0,0,0,.7);

  }
}
</style>

